var express = require("express");
var app = express();
require("express-ws")(app);

var port = 7777;
var clientObject = {};
var rooms = {};
app.ws("/", (client, req) => {
  // 连接
  console.log("req:", req);

  var key = req.socket.remoteAddress + "_" + req.socket.remotePort;
  console.log("key:", key);

  clientObject[key] = {
    cli: client,
    heartBeat: 1,
  };
  console.log(clientObject);

  // 消息
  client.on("message", (message) => {
    client.send("收到你的消息了" + message);
  });
  // 关闭
  client.on("close", () => {
    var key = req.socket.remoteAddress + "_" + req.socket.remotePort;
    if (clientObject[key]) {
      delete clientObject[key];
    }
  });
  // 错误
  client.on("error", () => {});
});

// app.get("/", (req, res) => {
//   res.send("hello 2023");
// });
app.listen(port);

// 心跳
setInterval(() => {
  var time = Date.now();
  for (var key in clientObject) {
    var client = clientObject[key].cli;
    var heartBeat = clientObject[key].heartBeat;
    clientObject[key].heartBeat += 1;
    try {
      var sData = {
        rspdata: {
          heartBeat: heartBeat,
          time: time,
        },
      };
      client.send(JSON.stringify(sData));
    } catch (e) {}
  }
}, 1000 * 3);
